package com.example.springboottestgit.service;

import com.alibaba.fastjson.JSONObject;
import com.example.springboottestgit.bean.BusinessException;
import com.example.springboottestgit.bean.CommonException;
import com.example.springboottestgit.bean.QwenDocumentQaRecord;
import com.example.springboottestgit.bean.QwenDocumentUploadRecord;
import com.example.springboottestgit.bean.dto.CommonDTO;
import com.example.springboottestgit.bean.vo.CommonVO;
import com.example.springboottestgit.bean.vo.InputVO;
import com.example.springboottestgit.bean.vo.OutputVO;
import com.example.springboottestgit.dao.QwenDocumentQaRecordMapper;
import com.example.springboottestgit.dao.QwenDocumentUploadRecordMapper;
import com.example.springboottestgit.enums.ExceptionCodeEnum;
import com.example.springboottestgit.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: ZZZ
 */
@Slf4j
@Service
public class DocumentQAService {

    @Value("${qwen.file.upload.path}")
    private String fileUploadPath;

    @Value("${qwen.document.content.qa.url}")
    private String url;

    @Autowired
    private QwenDocumentQaRecordMapper qwenDocumentQaRecordMapper;

    @Autowired
    private QwenDocumentUploadRecordMapper qwenDocumentUploadRecordMapper;

    private Map<Long, String> map = new HashMap<>();


    public CommonVO fileUpload(MultipartFile multipartFile) {
        // 获取文件名 xxx.doc
        String fileName = multipartFile.getOriginalFilename().replace(" ", "");
        // 构建上传路径
        File dest = new File(fileUploadPath + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            // 保存文件
            log.info("========qwen 文档问答 文件上传==========");
            multipartFile.transferTo(dest);

            //fileName = UUID.randomUUID() + suffixName;
            long timestamp = System.currentTimeMillis();
            map.put(timestamp, fileUploadPath + fileName);

            QwenDocumentUploadRecord insert = new QwenDocumentUploadRecord();
            insert.setId(timestamp);
            insert.setFileName(fileName);
            insert.setFilePath(fileUploadPath + fileName);

            qwenDocumentUploadRecordMapper.insert(insert);

            CommonVO commonVO = new CommonVO();
            commonVO.setFileId(timestamp);
            return commonVO;
        } catch (IOException e) {
            throw new CommonException("001001", "文件上传失败");
        }
    }


    public CommonVO documentContentQa(CommonDTO dto) {

        QwenDocumentQaRecord insert = new QwenDocumentQaRecord();
        insert.setFileId(dto.getFileId());
        insert.setQuestion(dto.getQuestion());

       /* QwenDocumentUploadRecord uploadRecord = qwenDocumentUploadRecordMapper.selectById(dto.getFileId());
        if (uploadRecord == null) {
            throw new CommonException(ExceptionCodeEnum.QUERY_NO_RESULT.code, "文件不存在");
        }
        */

        InputVO vo = new InputVO();
        vo.setQuestion(dto.getQuestion());
        vo.setFilePath("/home/zhengzhenzhuang/models/qwen/document/data_test.txt");
        String param = JSONObject.toJSONString(vo);
        log.info("qwen 文档问答 问题：" + dto.getQuestion());
        log.info("qwen 文档问答 参数：" + param);


        String result = null;
        OutputVO out = null;
        try {
            result = HttpUtils.post(url, param);
            out = JSONObject.parseObject(result, OutputVO.class);
            insert.setStatus(1);
            insert.setAnswer(out.getAnswer());
            long id = qwenDocumentQaRecordMapper.insert(insert);
        } catch (Exception e) {
            insert.setStatus(2);
            qwenDocumentQaRecordMapper.insert(insert);
            log.error("qwen 文档问答 接口调用失败", e);
            throw new BusinessException(ExceptionCodeEnum.INTERFACE_CALL_FAIL.code, "qwen 文档问答 接口调用失败");
        }

        log.info("qwen 文档问答 回答：" + out.getAnswer());
        CommonVO commonVO = new CommonVO();
        commonVO.setFileId(dto.getFileId());
        commonVO.setQuestion(dto.getQuestion());
        commonVO.setAnswer(out.getAnswer());
        return commonVO;
    }

}
